package com.wxmp.userwechat.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.wxmp.userwechat.service.SysUserWechatService;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import springfox.documentation.annotations.ApiIgnore;

/**
 *  微信controller
 * @author song.wang
 * @date 2019年1月21日
 */
@ApiIgnore
@RestController
@RequestMapping("/wechat")
public class WechatController {
	private static final Logger logger = LoggerFactory.getLogger(WechatController.class);
	@Autowired
	private WxMpService wxService;
	@Value("${wechat.mp.url}")
	private String wxUrl;
	@Value("${wechat.mp.appid}")
	private String wxAppId;
	@Autowired
	private SysUserWechatService sysUserWechatService;

	@RequestMapping(value = { "authorize/{referenceCode}", "authorize" }, method = RequestMethod.GET)
	public ModelAndView authorize(@PathVariable(required = false) String referenceCode, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("【微信网页授权】根据来源场景判断是哪个微信菜单---【{}】", referenceCode);
		String url = wxUrl + "/sfp-admin/wechat/userInfo";
		String authorizeURL = wxService.switchoverTo(wxAppId).oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO,
				referenceCode);
		// String authorizeURL = wxService.oauth2buildAuthorizationUrl(url,
		// WxConsts.OAuth2Scope.SNSAPI_BASE, referenceCode);
		logger.info("【微信网页授权】获取code,authorizeURL={}", authorizeURL);
		return new ModelAndView(new RedirectView(authorizeURL));
	}

	@GetMapping("userInfo")
	public ModelAndView userInfo(@RequestParam("code") String code, @RequestParam("state") String state)
			throws Exception {
		logger.info("【微信网页授权】code={}", code);
		logger.info("【微信网页授权】自定义参数state={}", state);

		WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
		try {
			wxMpOAuth2AccessToken = wxService.switchoverTo(wxAppId).oauth2getAccessToken(code);
		} catch (WxErrorException e) {
			logger.info("【微信网页授权】{}", e);
			throw new Exception(e.getError().getErrorMsg());
		}
		String openId = wxMpOAuth2AccessToken.getOpenId();
		logger.info("【微信网页授权】openId={}", openId);
		String mobileBindUrl = "/sfp-admin/wxpage/bind/adduser.html";
		if ("electricBorrow".equals(state)) {
			// 电气借用
			int count = sysUserWechatService.countByOpenid(openId);
			if (count == 0) {
				// 未绑定微信，跳转到微信绑定页面
				mobileBindUrl = wxUrl + "/sfp-portal/mobile/bind.html?jump=electricBorrow";
			} else {
				mobileBindUrl = wxUrl + "/sfp-portal/mobile/electricBorrow/home.html";
			}
		} else if ("receiving".equals(state)) {
			// 收货管理
			int count = sysUserWechatService.countByOpenid(openId);
			if (count == 0) {
				// 未绑定微信，跳转到微信绑定页面
				mobileBindUrl = wxUrl + "/sfp-portal/mobile/bind.html?jump=receiving";
			} else {
				mobileBindUrl = wxUrl + "/sfp-portal/mobile/receiving/home.html";
			}
		}
		return new ModelAndView(
				new RedirectView(mobileBindUrl + (mobileBindUrl.indexOf("?") == -1 ? "?" : "&") + "oid=" + openId));

	}

	

}